<template>
  <div ref="container" class="markdown-content">
    <div v-if="!renderedContent" class="default-message">
      <img
        class="w-[260px] h-[160px] mx-auto opacity-[var(--ai-box-image-opacity)]"
        src="@/assets/images/no-data.png"
      />
      <span class="text-[var(--base-left-menu-btn-color)] text-xs">暂时没有相关数据</span>
    </div>
    <div v-else v-html="renderedContent"></div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import * as marked from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/github.css"; // 引入代码高亮样式
import DOMPurify from "dompurify"; // 用于安全过滤

// 配置 Markdown 解析
const highlightExtend = (code) => {
  try {
    return hljs.highlightAuto(code).value;
  } catch (e) {
    return code;
  }
};

marked.use({
  breaks: true,
  highlight: highlightExtend,
  langPrefix: "hljs language-",
});

// 安全净化配置
const sanitizeConfig = {
  // ALLOWED_TAGS: ["p", "pre", "code", "blockquote" /* 其他允许的标签 */],
  // FORBID_ATTR: ["style", "class"],
};

// 组件逻辑
const props = defineProps({
  content: {
    type: String,
    default: "",
  },
  autoScroll: {
    type: Boolean,
    default: true,
  },
});

const container = ref(null);
const markdownCache = ref(new Map());

const safeRender = (content) => {
  if (!content) return "";
  try {
    const rawHtml = marked.parse(content);
    return DOMPurify.sanitize(rawHtml, sanitizeConfig);
  } catch (e) {
    console.error("Markdown 解析失败:", e);
    return content;
  }
};

// 带缓存的渲染
const renderedContent = computed(() => {
  if (markdownCache.value.has(props.content)) {
    return markdownCache.value.get(props.content);
  }
  const result = safeRender(props.content);
  markdownCache.value.set(props.content, result);
  return result;
});

// 自动滚动到底部
watch(
  () => props.content,
  () => {
    if (props.autoScroll && container.value) {
      nextTick(() => {
        container.value.scrollTop = container.value.scrollHeight;
      });
    }
  }
);

// 初始化高亮
onMounted(() => {
  hljs.configure({
    ignoreUnescapedHTML: true, // 防止与 Vue 的 DOM 处理冲突
  });
});
</script>

<style lang="scss">
.markdown-content {
  height: calc(100vh - 180px);
  overflow-y: auto;
  padding: 1rem;
  line-height: 1.6;

  /* 基础排版样式 */
  h1,
  h2,
  h3 {
    margin: 1em 0;
    border-bottom: 1px solid #eee;
  }

  pre {
    padding: 1rem;
    background: #f8f8f8;
    border-radius: 4px;
    overflow-x: auto;
  }

  code {
    font-family: "Fira Code", monospace;
    font-size: 0.9em;
  }

  /* 响应式处理 */
  @media (max-width: 768px) {
    height: calc(100vh - 150px);
    padding: 0.5rem;
  }
}

.default-message {
  text-align: center;
  color: #666;
  padding: 6rem;
}
</style>
